library("quantmod");
# rm(list=ls())
# Load stock symbols from List
Debug = F;
scan_stock = function(ListFile) {
    stock_list = read.csv(ListFile, colClasses="character", head=F);
    re = "";
    for (stock_name in stock_list$V1) {
		to = Sys.Date();
    	from = to - 150;
    	stock = getSymbols(stock_name, src="yahoo", auto.assign=F);


        result = check_stock(Debug, stock[,4]);
        re = c(re, result);
    }
    write(re, "result_sim.txt");
}

check_stock = function(Debug, stock_close) {
    orig_gain = 0;
    result = "";
    X = c(8, 12, 20);
    Y = c(20, 30, 40);
    Z = c(8, 13, 20, 29)
    profit_result = -2;
    perf_result = 0;
    param_result=c(0,0,0);
    try({

    total_length = length(stock_close);
    final_price = stock_close[total_length];
    init_price = stock_close[total_length-80];
    class(final_price) <- "numeric";
    class(init_price) <- "numeric";
    orig_gain = (final_price - init_price) / init_price;

    for (fast in X) {
    for (slow in Y) {
    for (signal in Z) {
        profit = c();
	
		#print(paste( "x:",fast,"y:", slow, "z:", signal ))	
        stock_macd = MACD(stock_close, fast, slow, signal);
        stock_macd_diff = stock_macd[,1] - stock_macd[,2];
        stock_BB = BBands(stock_close, n=10);

        recur = total_length - 80;
        while (recur <= total_length) {
            buy = buy(Debug, recur, stock_close, stock_macd[,1], stock_macd[,2], stock_macd_diff);    
            if (buy == T) {
                #if (Debug == T) {print( stock_close[recur] )}; 
                sell_pos = recur;
                while(sell_pos <= total_length) {
                    sell = sell(Debug, sell_pos, stock_close, stock_macd[,1], stock_macd[,2], stock_macd_diff, stock_BB);
                    if (recur == total_length) {sell = T;}
                    if (sell == T) {
                        buy_price = stock_close[recur];
                        sell_price = stock_close[sell_pos];
                        class(buy_price) <- "numeric";
                        class(sell_price) <- "numeric";
                        this_profit = (sell_price-buy_price) / buy_price;
                        profit = c(profit, this_profit);
                        if (Debug == T) {
                            #print(stock_close[sell_pos]);
                            print(paste("Profit = ", this_profit, "interval = ", sell_pos - recur));
                            print("--------------------------------------------------------------------");
                        }
                        recur = sell_pos;
                        break;
                    }
                    sell_pos = sell_pos + 1;
                } # end of find sell position
            }
            # Next 
            recur = recur + 1;
        } # End of Recur
        if (Debug == F) { rm(stock_macd, stock_BB, stock_macd_diff); }
        if (Debug == T) { print(profit); }
        profit_this = sum(profit);
		performance = (profit_this - orig_gain) ;
        
		if (profit_this > profit_result) { 
            profit_result = profit_this; 
            perf_result = performance; 
            param_result = c(fast, slow, signal);
            result = paste("profit sum = ",  profit_this, ", count = " , length(profit), ", Perf = ", performance, ", param = ", fast, ",", slow, ",", signal );
         }
    } # End of X
    } # End of Y
    } # End of Z
    }) # end of try
    if (Debug==T) { print(result) };
    return ( param_result );
}

buy = function(debug, pos, price, macd, macd_signal, macd_diff) {
    result = T;
    latest_macd = macd[pos];
    latest_signal = macd_signal[pos];
    latest_signal_1 = macd_signal[pos-1];
    latest_signal_2 = macd_signal[pos-2];
    latest_signal_3 = macd_signal[pos-3];
    latest_signal_4 = macd_signal[pos-4];
    latest_signal_5 = macd_signal[pos-5];
    latest_price = price[pos];
    latest_price_1 = price[pos-3];

    bar1 = macd_diff[pos];
    bar2 = macd_diff[pos-1];
    bar3 = macd_diff[pos-2];
    bar4 = macd_diff[pos-3];
    bar5 = macd_diff[pos-4];


    class (latest_signal) <- "numeric";
    class (latest_signal_1) <- "numeric";
    class (latest_signal_2) <- "numeric";
    class (latest_signal_3) <- "numeric";
    class (latest_signal_4) <- "numeric";
    class (latest_signal_5) <- "numeric";
    class(bar1) <- "numeric";
    class(bar2) <- "numeric";
    class(bar3) <- "numeric";
    class(bar4) <- "numeric";
    class(bar5) <- "numeric";
      vol         <- "numeric";
      vol_1       <- "numeric";

    diff1 = bar1 - bar2;
    diff2 = bar2 - bar3;
    diff3 = bar3 - bar4;
    diff4 = bar4 - bar5;

    macd_signal_diff   =   latest_signal - latest_signal_1;
    macd_signal_diff_1 = latest_signal_1 - latest_signal_2;
    macd_signal_diff_2 = latest_signal_2 - latest_signal_3;
    macd_signal_diff_3 = latest_signal_3 - latest_signal_4;
    macd_signal_diff_4 = latest_signal_4 - latest_signal_5;


    class(latest_price) <- "numeric";
    class(latest_price_1) <- "numeric";
    latest_price_change = latest_price - latest_price_1;
    result = F;

    if 
    (
        macd_signal_diff > 0 && macd_signal_diff_1 > 0
    )
    {
        result = T;
        if (macd_signal_diff_3 > 0 && macd_signal_diff_4 > 0) { result = F; }
        if (diff1 < 0 && diff2 < 0) { result = F; }
        if (price[recur] < 7) { result = F; }
        
    }
    return (result);
}

sell = function(debug, pos, price, macd, macd_signal, macd_diff, bband) {
    sell_bar1 = macd_diff[pos];
    sell_bar2 = macd_diff[pos-1];
    sell_bar3 = macd_diff[pos-2];
    sell_macd = macd[pos,1];

    sell_signal = macd_signal[pos];
    sell_signal_1 = macd_signal[pos-1];
    sell_signal_2 = macd_signal[pos-2];

    sell_price = price[pos];
    sell_price_1 = price[pos-1];
    sell_price_2 = price[pos-2];
    sell_price_3 = price[pos-3];

    class(sell_price)     <- "numeric";
    class(sell_price_2)     <- "numeric";
    class(sell_bar1)     <- "numeric";
    class(sell_bar2)     <- "numeric";
    class(sell_bar3)     <- "numeric";
    class(sell_signal)     <- "numeric";
    class(sell_signal_1)     <- "numeric";
    class(sell_signal_2)	<- "numeric";

    sell_diff1 = sell_bar1 - sell_bar2;
    sell_diff2 = sell_bar2 - sell_bar3;
    
    sell_signal_diff = sell_signal - sell_signal_1;
    sell_signal_diff_1 = sell_signal_1 - sell_signal_2;
    
    sell_price_change_1 = (sell_price - sell_price_1) / sell_price;
    sell_price_change_2 = (sell_price - sell_price_2) / sell_price;
    sell_price_change_3 = (sell_price - sell_price_3) / sell_price;

    result = F;
    #print(sell_signal_diff < 0); print( sell_signal_diff_1 < 0);
    if (
        sell_signal_diff < 0 && sell_signal_diff_1 < 0 #&& (sell_price > bband[pos, 1])    

    ) {
        result = T;
    }

    return (result);
}
